import UnitUtil from '@/UnitUtil';
import BuffUtil from '@/BuffUtil';

export default class ShieldSystem {
    private 配置: Map<unit, Map<string, { value: number; buffId: string; from: unit }>> = new Map();
    constructor() {
        se.onUnitDeath(this.deathAciont.bind(this));
        EventManager.onTakeDamage(this.护盾处理.bind(this));
    }
    deathAciont(ev: any) {
        let u = GetTriggerUnit();
        if (!UnitUtil.isHero(u)) {
            this.配置.delete(u);
        }
    }
    护盾处理(数据: DamageEventData) {
        let 护盾值 = this.获取总护盾值(数据.target);
        if (护盾值 > 0) {
            let 护盾数据 = this.配置.get(数据.target);
            if (护盾数据 != null) {
                for (let item of 护盾数据) {
                    let [key, value] = item;
                    if (数据.lastDamage < value.value) {
                        value.value -= 数据.lastDamage;
                        护盾数据.set(key, value);
                        数据.lastDamage = 0;
                        break;
                    } else {
                        数据.lastDamage -= value.value;
                        this.移除指定技能护盾(数据.target, value);
                    }
                }
            }
        }
    }
    获取总护盾值(目标: unit): number {
        let map = this.配置.get(目标);
        if (map != null) {
            let v = map.values();
            let total = 0;
            for (let val of v) {
                total += val.value;
            }
            return total;
        } else {
            return 0;
        }
    }
    获取按指定技能护盾值(目标: unit, 护盾技能id: string): number | null {
        let map = this.配置.get(目标);
        if (map != null) {
            return map.get(护盾技能id)?.value ?? 0;
        } else {
            return 0;
        }
    }
    添加护盾值(目标: unit, buffId: string, 数值: number, 叠加: boolean, from: unit) {
        if (this.配置.get(目标) == null) {
            this.配置.set(目标, new Map());
        }
        let key = this.getKey(buffId, from);
        if (叠加) {
            let map = this.配置.get(目标);
            let 剩余 = map.get(key)?.value ?? 0;
            this.配置.get(目标).set(key, { value: 剩余 + 数值, buffId, from });
        } else {
            this.配置.get(目标).set(key, { value: 数值, buffId, from });
        }
    }
    private 移除指定技能护盾(目标: unit, d: { buffId: string; from: unit }) {
        let s = this.配置.get(目标);
        let key = this.getKey(d.buffId, d.from);
        s?.delete(key);
        // 删除buff
        if (BuffUtil.hasUnitBuff(目标, d.buffId, d.from)) BuffUtil.clearUnitBuff(目标, d.buffId, d.from);
    }
    移除指定护盾(目标: unit, buffId: string, from: unit) {
        let s = this.配置.get(目标);
        let key = this.getKey(buffId, from);
        s?.delete(key);
    }
    getKey(buffId: string, u: unit) {
        return `${buffId}_${GetHandleId(u)}`;
    }
}
